<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { queryByEmpNameApi, updateStatusApi } from '@/api/maintenance'
import { updateEmployeeStatusApi } from '@/api/emp'

// 搜索条件
const searchParams = ref({
  userName: '',
  status: '',
  dateRange: [],
  beginDate: '',
  endDate: ''
})

// 监听日期范围变化
watch(
  () => searchParams.value.dateRange,
  (newValue) => {
    if(newValue.length === 2){
      searchParams.value.beginDate = newValue[0]
      searchParams.value.endDate = newValue[1]
    } else {
      searchParams.value.beginDate = ''
      searchParams.value.endDate = ''
    }
  }
)

// 预约状态选项
const statusOptions = ref([
  { label: '待确认', value: '待确认' },
  { label: '已确认', value: '已确认' },
  { label: '工作中', value: '工作中' },
  { label: '已完成', value: '已完成' },
  { label: '已取消', value: '已取消' }
])

// 分页配置
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const appointmentList = ref([])
const empName = ref('')

// 状态已经使用formatStatus函数处理，这里不再需要getStatusText

// 根据状态获取标签类型 

const getTagType = (status) => { 

const typeMap = { 

'待确认': 'warning', 

'已确认': 'primary', 

'工作中': 'info', 

'已完成': 'success', 

'已取消': 'danger' 

}; 

return typeMap[status] || 'info'; 

};

// 格式化状态显示 

const formatStatus = (status) => { 

const statusMap = { 

'待确认': '待确认', 

'已确认': '已确认', 

'工作中': '工作中', 

'已完成': '已完成', 

'已取消': '已取消' 

}; 

return statusMap[status] || status; 

};

// 查询数据
const handleSearch = async () => {
  try {
    let loginUser = JSON.parse(localStorage.getItem('loginUser'))
    const result = await queryByEmpNameApi(loginUser.name)
    
    if(result.code) {
      let filteredData = result.data
      
      // 应用过滤条件
      if (searchParams.value.userName) {
        filteredData = filteredData.filter(item => 
          item.userName && item.userName.includes(searchParams.value.userName)
        )
      }
      

      
      if (searchParams.value.status) {
        filteredData = filteredData.filter(item => 
          item.status === searchParams.value.status
        )
      }
      
      if (searchParams.value.beginDate) {
        filteredData = filteredData.filter(item => 
          item.appointmentDate >= searchParams.value.beginDate
        )
      }
      
      if (searchParams.value.endDate) {
        filteredData = filteredData.filter(item => 
          item.appointmentDate <= searchParams.value.endDate
        )
      }
      
      // 排序：按预约时间降序
      filteredData.sort((a, b) => {
        return new Date(b.createdAt) - new Date(a.createdAt)
      })
      
      appointmentList.value = filteredData
      total.value = filteredData.length
    } else {
      ElMessage.error(result.msg || '查询失败')
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试')
  }
  console.log(appointmentList.value)
}

// 重置搜索条件
const handleReset = () => {
  searchParams.value = {
    userName: '',
    status: '',
    dateRange: [],
    beginDate: '',
    endDate: ''
  }
  currentPage.value = 1
  handleSearch()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 处理保养操作（从确认到工作中，或从工作中到完成）
const handleMaintenanceAction = async (row) => {
  try {
    // 根据当前状态决定下一个状态
    const nextStatus = row.status === '已确认' ? '工作中' : '已完成';
    const result = await updateStatusApi({
      id: row.id,
      status: nextStatus,
      empName: row.empName
    })
    
    if (result.code) {
      ElMessage.success(nextStatus === '工作中' ? '已开始保养' : '保养已完成')
      
      // 如果任务标记为已完成，更新员工状态为空闲
      if (nextStatus === '已完成') {
        const loginUser = JSON.parse(localStorage.getItem('loginUser'))
        if (loginUser) {
          await updateEmployeeStatusApi(loginUser.id)
        }
      }
      
      handleSearch()
    } else {
      ElMessage.error(result.msg || '更新失败')
    }
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('网络错误，请稍后重试')
  }
}

onMounted(() => {
  // 获取登录用户名
  let loginUser = JSON.parse(localStorage.getItem('loginUser'))
  if (loginUser) {
    empName.value = loginUser.name
  }
  handleSearch()
})
</script>

<template>
  <div class="maintenance-management">
    <h1>我的保养预约</h1>
    <br>
    
    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchParams" class="search-form">
      <el-form-item label="用户姓名">
        <el-input v-model="searchParams.userName" placeholder="请输入用户姓名"></el-input>
      </el-form-item>
      

      
      <el-form-item label="预约状态">
        <el-select v-model="searchParams.status" placeholder="请选择" style="width: 120px;">
          <el-option label="全部" value=""></el-option>
          <el-option v-for="option in statusOptions" :key="option.value" 
                    :label="option.label" :value="option.value"></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="预约日期">
        <el-date-picker
          v-model="searchParams.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        ></el-date-picker>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>查询
        </el-button>
        <el-button @click="handleReset">
          <el-icon><Refresh /></el-icon>清空
        </el-button>
      </el-form-item>
    </el-form>
    <br>
    
    <!-- 数据表格 -->
    <el-table :data="appointmentList" border style="width: 100%" fit :max-height="600" show-overflow-tooltip>
      <el-table-column type="index" label="序号" width="60" align="center"/>
      <el-table-column prop="userName" label="用户姓名" width="120" align="center"></el-table-column>
      <el-table-column prop="contactPhone" label="联系电话" width="120" align="center"></el-table-column>
      <el-table-column prop="plateNumber" label="车牌号" width="100" align="center"></el-table-column>
      <el-table-column prop="appointmentDate" label="预约日期" width="100" align="center"></el-table-column>
      <el-table-column prop="appointmentTime" label="预约时间" width="100" align="center"></el-table-column>
      <el-table-column prop="description" label="保养描述" width="250" align="center"></el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="170" align="center"></el-table-column>
      <el-table-column label="预约状态" width="85" align="center">
        <template #default="scope">
          <el-tag :type="getTagType(scope.row.status)">{{ formatStatus(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
        <el-table-column label="操作" fixed="right" align="center">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="handleMaintenanceAction(scope.row)"
              v-if="['已确认', '工作中'].includes(scope.row.status)"
            >
              {{ scope.row.status === '已确认' ? '处理' : '已完成' }}
            </el-button>
          </template>
        </el-table-column>
    </el-table>
    <br>
    
    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 20, 30]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
  </div>
</template>

<style scoped>
.maintenance-management {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}
</style>